package com.cckat.service.impl;

import com.cckat.base.BaseMapper;
import com.cckat.base.BaseServiceImpl;
import com.cckat.entity.Permission;
import com.cckat.entity.Role;
import com.cckat.mapper.AdminRoleMapper;
import com.cckat.mapper.PermissionMapper;
import com.cckat.mapper.RoleMapper;
import com.cckat.mapper.RolePermissionMapper;
import com.cckat.service.RoleService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author 静海基地
 */
@DubboService
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public BaseMapper<Role> getBaseMapper(){
        return roleMapper;
    }


    @Override
    public Map<String, List<Role>> findRoleList(Long adminId) {
        //查询所有的角色信息
        List<Role> allRoleList = roleMapper.findAll();
        //查询用户已经分配的角色的id集合
        List<Long> assignRoleIdList = roleMapper.getRoleIdListByAdminId(adminId);
        //创建存储已分配和未分配角色信息的集合
        List<Role> unAssignRoleList = new ArrayList<>();
        List<Role> assignRoleList = new ArrayList<>();
        for (Role role : allRoleList) {
            if(assignRoleIdList.contains(role.getId())){
                assignRoleList.add(role);
            }else{
                unAssignRoleList.add(role);
            }
        }
        Map<String, List<Role>> map = new HashMap<>();
        map.put("unAssignRoleList", unAssignRoleList);
        map.put("assignRoleList", assignRoleList);
        return map;
    }

    @Override
    public List<Map<String, Object>> findZnodes(Long roleId) {
        //获取所有权限信息
        List<Permission> allPermissionList = permissionMapper.findAll();
        //获取角色所拥有的权限的id集合
        List<Long> permissionIdList = rolePermissionMapper.findPermissionIdListByRoleId(roleId);

        //创建一个集合存储最终的数据
        List<Map<String, Object>> permissionList = new ArrayList<>();
        for (Permission permission : allPermissionList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", permission.getId());
            map.put("pId", permission.getParentId());
            map.put("name", permission.getName());
            if(permissionIdList.contains(permission.getId())){
                map.put("checked", true);
            }
            permissionList.add(map);
        }
        return permissionList;
    }

    @Override
    public void assignPermission(Long roleId, List<Long> permissionIds) {
        //先将中间表中角色和权限的关系删除
        rolePermissionMapper.deleteByRoleId(roleId);
        //重新为角色分配权限
        rolePermissionMapper.assignPermission(roleId, permissionIds);
    }
}
